<template>
  <div>
    <el-form
      ref="formRef4"
      :model="formInlineNosubmit"
      :rules="rules"
      class="form-inline"
      label-width="auto"
      label-position="top"
      :disabled="isDisabled"
    >
      <el-form-item
        v-for="(item, index) in form4"
        :key="index"
        :label="item.label"
        :prop="item.prop"
      >
        <!-- input -->
        <el-input
          v-if="item.type === 'input'"
          v-model="formInlineNosubmit[item.prop]"
          placeholder="请输入"
          :disabled="isDisabled"
          clearable
        />
      </el-form-item>
    </el-form>
    <vxe-grid
      ref="xGrid"
      v-bind="gridOptions"
      :height="height"
      style="width: 100%; margin-top: 20px"
    >
      <template #operate="{ row }">
        <template v-if="hasActiveEditRow(row)">
          <vxe-button content="取消" @click="clearRowEvent" />
          <vxe-button
            status="primary"
            content="保存"
            :disabled="isDisabled"
            @click="saveRowEvent(row)"
          />
        </template>
        <template v-else>
          <vxe-button
            content="编辑"
            :disabled="isDisabled"
            @click="editRowEvent(row)"
          />
        </template>
        <vxe-button
          status="danger"
          content="删除"
          :disabled="isDisabled"
          @click="removeRowEvent(row)"
        />
      </template>
      <template #year_edit="{ row }">
        <el-date-picker
          v-model="row.year"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          type="date"
          placeholder="请选择"
        />
      </template>
      <template #profit_edit="{ row }">
        <el-input
          v-model.number="row.profit"
          @input="handChange($event, row)"
        />
      </template>
      <template #conserve_edit="{ row }">
        <el-input
          v-model.number="row.conserve"
          @input="handChange($event, row)"
        />
      </template>
    </vxe-grid>
    <el-button
      type="primary"
      text
      :icon="Plus"
      :disabled="isDisabled"
      @click="addInventor"
    >
      增加行
    </el-button>
    <el-form
      ref="formRef41"
      :model="formInline"
      :rules="rules"
      class="form-inline mt20"
      label-width="auto"
      label-position="top"
      :disabled="isDisabled"
    >
      <el-form-item
        v-for="(item, index) in form41"
        :key="index"
        :label="item.label"
        :prop="item.prop"
      >
        <!-- textarea -->
        <el-input
          v-if="item.type === 'textarea'"
          v-model="formInline[item.prop]"
          placeholder="请输入"
          :rows="4"
          type="textarea"
          clearable
        />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
  import {
    ref,
    reactive,
    defineExpose,
    defineProps,
    onMounted,
    withDefaults,
    watch,
  } from 'vue'
  import {
    form4,
    form4GridOptions,
    form41,
    form4CraftOPtions,
  } from '../table/column'
  import { Delete, Plus } from '@element-plus/icons-vue'
  import {
    VXETable,
    VxeGridInstance,
    VxeGridProps,
    VxeGridListeners,
  } from 'vxe-table'
  import { useAchievementAwardStore } from '@/store/modules/achievementAward'
  import { storeToRefs } from 'pinia'

  const props = withDefaults(
    defineProps<{
      isDisabled?: boolean
      isUpdate?: boolean
      isCraft?: string
    }>(),
    {
      isDisabled: false,
      isUpdate: false,
      isCraft: '研发类',
    }
  )

  const gridOptions = computed(() => {
    return props.isCraft == '研发类'
      ? form4GridOptions.value
      : form4CraftOPtions.value
  })

  const formRef4 = ref()
  const formRef41 = ref()
  const formInline = ref<any>({})
  const formInlineNosubmit = ref({})
  const rules = reactive({})
  const xGrid = ref()
  const store = useAchievementAwardStore()
  const { addForm } = store
  const { allForm } = storeToRefs(store)

  watch(
    () => props.isUpdate,
    (val) => {
      for (const key in allForm.value) {
        formInline.value[key] = allForm.value[key]
      }
      const economicBenefitsTable = JSON.parse(
        formInline.value.economicBenefitsTable
      )
      formInlineNosubmit.value = economicBenefitsTable.formInlineNosubmit
      formInline.value.economicBenefitsTable = economicBenefitsTable
      gridOptions.value.data = economicBenefitsTable.tableData
    }
  )

  const submit = async () => {
    const isOk = [false, false]
    await formRef4.value.validate((valid) => {
      if (valid) {
        return (isOk[0] = true)
      } else {
        console.log('error submit!!')
        return (isOk[0] = false)
      }
    })

    await formRef41.value.validate((valid) => {
      if (valid) {
        return (isOk[1] = true)
      } else {
        console.log('error submit!!')
        return (isOk[1] = false)
      }
    })

    if (isOk[0] == true && isOk[1] == true) {
      formInline.value.economicBenefitsTable = xGrid.value.getTableData()
      formInline.value.economicBenefitsTable.formInlineNosubmit =
        formInlineNosubmit.value
      formInline.value.economicBenefitsTable = JSON.stringify(
        formInline.value.economicBenefitsTable
      )
      addForm(formInline.value)
    }
  }

  const hasActiveEditRow = (row) => {
    const $grid = xGrid.value
    if ($grid) {
      return $grid.isEditByRow(row)
    }
    return false
  }
  const editRowEvent = (row) => {
    const $grid = xGrid.value
    if ($grid) {
      $grid.setEditRow(row)
    }
  }

  const saveRowEvent = async (row) => {
    const $grid = xGrid.value
    if ($grid) {
      await $grid.clearEdit()
      // form4GridOptions.loading = true
      // // 模拟异步保存
      // setTimeout(() => {
      //   form4GridOptions.loading = false
      // }, 300)

      // console.log(row)
      // row.total = row.conserve + row.profit
      // form4GridOptions.data.push(row)
    }
  }

  const clearRowEvent = () => {
    const $grid = xGrid.value
    if ($grid) {
      $grid.clearEdit()
    }
  }

  const removeRowEvent = async (row) => {
    const $grid = xGrid.value
    const type = await VXETable.modal.confirm('您确定要删除该数据?')
    if ($grid) {
      if (type === 'confirm') {
        await $grid.remove(row)
      }
    }
  }

  onMounted(() => {
    // if (JSON.stringify(props.formData) !== '{}') {
    //   formInline.value = props.formData
    // }
  })
  const addInventor = () => {
    const $grid = xGrid.value
    $grid.insert({})
  }

  const handChange = (value, row) => {
    row.total = Number(row.conserve) + Number(row.profit)
    return row.total
  }

  const tablePage = reactive({
    total: 0,
    currentPage: 1,
    pageSize: 10,
  })

  const handlePageChange = ({ currentPage, pageSize }) => {
    tablePage.currentPage = currentPage
    tablePage.pageSize = pageSize
    // findList()
  }

  const height = ref(0)
  interface BaseTableHeight {
    (padding: number): number
  }
  const $baseTableHeight = inject<BaseTableHeight>('$baseTableHeight')
  onBeforeMount(() => {
    window.addEventListener('resize', handleHeight)
  })

  onBeforeUnmount(() => {
    window.removeEventListener('resize', handleHeight)
  })

  const handleHeight = () => {
    height.value = $baseTableHeight(0)
  }

  const computeTotal = (row, a, b) => {
    row.total = (parseFloat(a) + parseFloat(b)).toFixed(2)
    return row
  }
  defineExpose({
    submit,
  })
</script>

<style scoped lang="scss">
  .form-inline {
    margin-top: 20px;
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-row-gap: 16px;
    grid-column-gap: 20px;

    .el-input {
      // --el-input-width: 323px;
    }

    .el-select {
      // --el-select-width: 323px;
    }

    :deep(.el-form-item__label) {
      padding: 0 5px 0 0;
    }

    :deep(.el-form-item) {
      margin-right: 0px;
      margin-bottom: 0px;
    }
  }

  .mt20 {
    margin-top: 20px;
  }
</style>
